package com.yuexunit.mobilenurse.module.BloodManage.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodManage.adapter.BloodSendAdapter;
import com.yuexunit.mobilenurse.module.BloodManage.bean.Blood;
import com.yuexunit.mobilenurse.module.BloodManage.bean.BloodDataBean;
import com.yuexunit.mobilenurse.module.BloodManage.bean.SingleBloodBag;
import com.yuexunit.mobilenurse.module.BloodManage.model.impl.BloodApplyModel;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.IBloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.presenter.impl.BloodApplyPresenter;
import com.yuexunit.mobilenurse.module.BloodManage.ui.Act_Blood_Detail_Cancle;
import com.yuexunit.mobilenurse.module.BloodManage.ui.Act_Blood_Main_Lachsis;
import com.yuexunit.mobilenurse.module.BloodManage.ui.view.IBloodApplyView;
import com.yuexunit.mobilenurse.widget.CustomDatePicker;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.FooterLoadingLayout;
import com.yuexunit.mobilenurse.widget.PullToRefreshBase;
import com.yuexunit.mobilenurse.widget.PullToRefreshList;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/4/9 0009.
 */

public class Frag_Blood_Cancle_Lachsis extends KJFragment implements IBloodApplyView {
    @Bind(R.id.patient_list)
    PullToRefreshList patientList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.tv_date_from)
    TextView tvDateFrom;
    @Bind(R.id.tv_date_to)
    TextView tvDateTo;

    protected View mMainView;
    private ListView mList;
    private BloodSendAdapter adapter;
    private int nowpage = 1;
    private int totalpage = 1;
    private int pagesize = 20;

    public static final int DOWNLOAD_SUCCESS = 1;
    public static final int DOWNLOAD_NODATA = 0;
    public static final int DOWNLOAD_NETERROR = -1;

    IBloodApplyPresenter presenter;

    ArrayList<Blood> bloods =new ArrayList<>();

    private Act_Blood_Main_Lachsis aty;

    Boolean isRefresh = false;
    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        aty = (Act_Blood_Main_Lachsis) getActivity();
        mMainView = inflater.inflate(R.layout.frag_things_list, container, false);
        ButterKnife.bind(this, mMainView);
        return mMainView;
    }

    @Override
    protected void initData() {
        super.initData();
        presenter = new BloodApplyPresenter(new BloodApplyModel(),this);
        listViewPreference();
        showDateDialog(3);
        ApiForGetList();
    }

    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        mList = patientList.getRefreshView();
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        patientList.setPullRefreshEnabled(true);
        patientList.setPullLoadEnabled(true);
        ((FooterLoadingLayout) patientList.getFooterLoadingLayout()).setNoMoreDataText("无更多数据");

        patientList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                isRefresh = true;
                nowpage = 1;
                ApiForGetList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (nowpage < totalpage) {
                    nowpage++;
                    ApiForGetList();
                } else {
                    patientList.setHasMoreData(false);
                    patientList.onPullUpRefreshComplete();
                }
            }
        });

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), Act_Blood_Detail_Cancle.class);
                intent.putExtra("requireNo", bloods.get(position).getRequireNo());
                startActivity(intent);
            }
        });
    }

    /**
     * 网络请求获取列表数据
     */
    private void ApiForGetList() {
        Map<String, String> params = new HashMap<>();
        params.put("cancleStatus","-1");
        params.put("areaNo", PreferenceHelper.readString(getActivity(), AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_NAME));
        params.put("inquireKey",etSearch.getText().toString());
        params.put("requireStartTime",tvDateFrom.getText().toString());
        params.put("requireEndTime",tvDateTo.getText().toString());
        params.put("pageIndex",nowpage+"");
        params.put("pageSize",pagesize+"");
        presenter.getBloodDataList(params);
    }

    private void showDateDialog(final int type) {
        if (type == 3) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
            String now = sdf.format(new Date());
            tvDateFrom.setText(now.substring(0,10)+" 00:00");
            tvDateTo.setText(now);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
            String now = sdf.format(new Date());

            CustomDatePicker customDatePicker = new CustomDatePicker(aty, new CustomDatePicker.ResultHandler() {
                @Override
                public void handle(String time) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                    Date selectTime = null;
                    try {
                        selectTime = sdf.parse(time);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if (type == 0) {
                        Date toDate = null;
                        try {
                            toDate = sdf.parse(tvDateTo.getText().toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (!selectTime.after(toDate)) {
                            tvDateFrom.setText(time);
                        } else {
                            ViewInject.toast("不能晚于结束时间");
                        }

                    } else if (type == 1) {
                        Date fromDate = null;
                        try {
                            fromDate = sdf.parse(tvDateTo.getText().toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (!selectTime.before(fromDate)) {
                            tvDateTo.setText(time);
                        } else {
                            ViewInject.toast("不能早于开始时间");
                        }
                    }
                }
            }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
            customDatePicker.setIsLoop(true); // 不允许循环滚动
//            customDatePicker.setCancelable(true);
//            customDatePicker.showSpecificDate(true);
            customDatePicker.showSpecificTime(true);
            customDatePicker.show(now);
        }
    }

    @OnClick({R.id.btn_search, R.id.ll_date_from, R.id.ll_date_to})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                bloods.clear();
                adapter.notifyDataSetChanged();
                isRefresh = true;
                nowpage=1;
                ApiForGetList();
                break;
            case R.id.ll_date_from:
                showDateDialog(0);
                break;
            case R.id.ll_date_to:
                showDateDialog(1);
                break;
        }
    }

    @Override
    public void showBloodDataList(BloodDataBean bloodDataBean) {
        if(bloodDataBean.getStatus().equals("200")) {
            totalpage = bloodDataBean.getTotalPageCount();
            if (bloods.size() > 0) {
                if(isRefresh)
                {
                    bloods.clear();
                    bloods.addAll(bloodDataBean.getDatas());
                    adapter.notifyDataSetChanged();
                    isRefresh=false;
                }
                else {
                    bloods.addAll(bloodDataBean.getDatas());
                    adapter.notifyDataSetChanged();
                }
            }
            else {
                if(null != bloodDataBean.getDatas()) {
                    bloods = bloodDataBean.getDatas();
                }
                else {
                    bloods = new ArrayList<>();
                }
                adapter = new BloodSendAdapter(mList, bloods, R.layout.item_blood_receive);
                mList.setAdapter(adapter);
                emptyLayout.dismiss();
            }
        }
    }

    @Override
    public void PullDownRefreshState(int state) {
        switch (state) {
            case DOWNLOAD_SUCCESS:
                patientList.onPullDownRefreshComplete();
                patientList.onPullUpRefreshComplete();
                break;
            case DOWNLOAD_NETERROR:
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                break;
            case DOWNLOAD_NODATA:
                emptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }

    @Override
    public void getBloodBagData(SingleBloodBag singleBloodBag) {

    }
}
